const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyParser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require('koa2-cors') //跨域配置
const session = require('koa-generic-session')//session配置

// 注册路由
const users = require('./routes/users')
const comment = require('./routes/comment')


// error handler
onerror(app)

// 服务端支持跨域
app.use(cors({
  // origin:支持前端哪个域,可以跨域;  credentials:允许跨域的时候带着 cookie
  origin: 'http://localhost:5173', credentials: true,Secure: true,SameSite:'None'
  // origin: '*' 允许所有请求跨域,但不能携带cookie
}))

// 配置 session
app.keys = ['dssUII^*(*123123']
app.use(session({
  // path:项目根路径下有效    httpOnly:只读   maxAge:有效时间,一天
  cookie: { path: '/', httpOnly: true, maxAge: 24 * 60 * 60 * 1000 }
}))

// middlewares
app.use(bodyParser({ enableTypes: ['json', 'form', 'text'] }))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', { extension: 'pug' }))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(users.routes(), users.allowedMethods())
app.use(comment.routes(), comment.allowedMethods())

// error-handling
app.on('error', (err, ctx) => console.error('server error', err, ctx))

module.exports = app
